package grafica;

import hotel.Autenticazione;
import hotel.Database;
import hotel.GestHotel;
import hotel.ImpostazioniXML;

import java.awt.Color;
import java.awt.EventQueue;

import javax.crypto.BadPaddingException;
import javax.crypto.IllegalBlockSizeException;
import javax.crypto.NoSuchPaddingException;
import javax.swing.*;

import java.awt.Font;

import javax.swing.border.BevelBorder;

import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.awt.Dimension;
import java.awt.Image;
import java.awt.Point;
import java.awt.Cursor;
import java.awt.Toolkit;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.PrintWriter;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.sql.SQLException;
import java.util.Scanner;

public class AccessoGrafica implements KeyListener,ActionListener {

	private JFrame frmAccesso;
	private JTextField usernameT;
	private JPasswordField passwordT;
	private JButton accedi;
	private JCheckBox cb;
	private JLabel nonRegistrato, passDimenticata, userDimenticata;
	private Database d;
	private JLabel caricamento;
	private JMenuBar barra;
	private JMenu impostazioni;
	private JMenuItem setup;
	private Color color=null;
	private ImpostazioniXML impo=new ImpostazioniXML();

	public static void main(String[] args) {
		System.setProperty("apple.laf.useScreenMenuBar", "true");
		EventQueue.invokeLater(new Runnable() {
			public void run() {
				try {
					AccessoGrafica window = new AccessoGrafica();
					window.frmAccesso.setVisible(true);
				} catch (Exception e) {
					e.printStackTrace();
				}
			}
		});
	}
	
	public void caricaColore() throws FileNotFoundException{
		String colore=impo.getColore();
		if(colore.equals("grigiochiaro")){
			color=Color.LIGHT_GRAY;
		}else if(colore.equals("rosso")){
			color=Color.RED;
		}else if(colore.equals("blu")){
			color=Color.BLUE;
		}else if(colore.equals("grigio")){
			color=Color.GRAY;
		}else if(colore.equals("giallo")){
			color=Color.YELLOW;
		}else if(colore.equals("nero")){
			color=Color.BLACK;
		}else if(colore.equals("bianco")){
			color=Color.WHITE;
		}else if(colore.equals("verde")){
			color=Color.GREEN;
		}
	}
	
	public void salvaColore() throws FileNotFoundException{
		String colore="";
		if(color==Color.LIGHT_GRAY){
			colore="grigiochiaro";
		}else if(color==Color.RED){
			colore="rosso";
		}else if(color==Color.BLUE){
			colore="blu";
		}else if(color==Color.GRAY){
			colore="grigio";
		}else if(color==Color.YELLOW){
			colore="giallo";
		}else if(color==Color.BLACK){
			colore="nero";
		}else if(color==Color.WHITE){
			colore="bianco";
		}else if(color==Color.GREEN){
			colore="verde";
		}
		impo.setColore(colore);
	}

	public AccessoGrafica() throws SQLException, IOException {
		d = new Database();
		initialize();
	}

	public AccessoGrafica(Database d) {
		this.d = d;
		initialize();
	}

	private void caricaUsernameEPassword() {
		if(impo.getSalvati()){
			cb.setSelected(true);
		}else cb.setSelected(false);
		usernameT.setText(impo.getUsername());
		passwordT.setText(impo.getPassword());
	}
	
	private void initialize() {
		try {
			caricaColore();
		} catch (FileNotFoundException e2) {
			e2.printStackTrace();
		}
		Image immagineIc = Toolkit.getDefaultToolkit().getImage(
				"Risorse/HOTEL.png");
		
//		MAC
		if (System.getProperty("os.name").equals("Mac OS X")) {
			  com.apple.eawt.Application application =
			  com.apple.eawt.Application.getApplication();
			  application.setDockIconImage(immagineIc);
		}
//		MAC
		
		frmAccesso = new JFrame();
		frmAccesso.setVisible(true);
		frmAccesso.setLocation(new Point(450, 100));
		frmAccesso.setSize(new Dimension(400, 350));
		frmAccesso.setResizable(false);
		frmAccesso.getContentPane().setBackground(color);
		String look = UIManager.getSystemLookAndFeelClassName();
		try {
			UIManager.setLookAndFeel(look);
		} catch (ClassNotFoundException | InstantiationException
				| IllegalAccessException | UnsupportedLookAndFeelException e1) {
			e1.printStackTrace();
		}
		frmAccesso.setBackground(Color.LIGHT_GRAY);
		frmAccesso.setTitle("Accesso");
		frmAccesso.setDefaultCloseOperation(JFrame.DO_NOTHING_ON_CLOSE);
		frmAccesso.addWindowListener(new WindowAdapter() {
			public void windowClosing(WindowEvent e) {
				frmAccesso.dispose();
				d.chiudiSocket();
				System.exit(0);
			}
		});
		//barra
		barra=new JMenuBar();
		impostazioni=new JMenu("Impostazioni");
		barra.add(impostazioni);
		setup=new JMenuItem("Setup");
		setup.addActionListener(this);
		impostazioni.add(setup);
		frmAccesso.setJMenuBar(barra);
		
		
		SpringLayout springLayout = new SpringLayout();
		frmAccesso.getContentPane().setLayout(springLayout);

		JLabel username = new JLabel("Username");
		springLayout.putConstraint(SpringLayout.NORTH, username, 10, SpringLayout.NORTH, frmAccesso.getContentPane());
		springLayout.putConstraint(SpringLayout.WEST, username, 149, SpringLayout.WEST, frmAccesso.getContentPane());
		springLayout.putConstraint(SpringLayout.EAST, username, -134, SpringLayout.EAST, frmAccesso.getContentPane());
		username.setHorizontalAlignment(SwingConstants.CENTER);
		username.setFont(new Font("Times New Roman", Font.PLAIN, 16));
		frmAccesso.getContentPane().add(username);

		JLabel password = new JLabel("Password");
		springLayout.putConstraint(SpringLayout.WEST, password, 149, SpringLayout.WEST, frmAccesso.getContentPane());
		springLayout.putConstraint(SpringLayout.EAST, password, 0, SpringLayout.EAST, username);
		password.setHorizontalAlignment(SwingConstants.CENTER);
		password.setFont(new Font("Times New Roman", Font.PLAIN, 16));
		frmAccesso.getContentPane().add(password);

		usernameT = new JTextField();
		springLayout.putConstraint(SpringLayout.NORTH, password, 6, SpringLayout.SOUTH, usernameT);
		springLayout.putConstraint(SpringLayout.NORTH, usernameT, 6, SpringLayout.SOUTH, username);
		springLayout.putConstraint(SpringLayout.WEST, usernameT, 0, SpringLayout.WEST, username);
		springLayout.putConstraint(SpringLayout.EAST, usernameT, -134,
				SpringLayout.EAST, frmAccesso.getContentPane());
		usernameT.setFont(new Font("Times New Roman", Font.PLAIN, 14));
		usernameT.setBorder(new BevelBorder(BevelBorder.LOWERED, null, null,
				null, null));
		frmAccesso.getContentPane().add(usernameT);
		usernameT.setColumns(10);

		passwordT = new JPasswordField();
		springLayout.putConstraint(SpringLayout.NORTH, passwordT, 6, SpringLayout.SOUTH, password);
		springLayout.putConstraint(SpringLayout.WEST, passwordT, 0, SpringLayout.WEST, username);
		springLayout.putConstraint(SpringLayout.EAST, passwordT, -134, SpringLayout.EAST, frmAccesso.getContentPane());
		passwordT.setFont(new Font("Times New Roman", Font.PLAIN, 14));
		passwordT.setBorder(new BevelBorder(BevelBorder.LOWERED, null, null,
				null, null));
		frmAccesso.getContentPane().add(passwordT);

		cb=new JCheckBox("Salva Username e Password");
		cb.setSelected(false);
		cb.addActionListener(new ActionListener(){
			@Override
			public void actionPerformed(ActionEvent e) {
				if(cb.isSelected()){
					impo.setSalvati(true);
					impo.setUsername(usernameT.getText());
					impo.setPassword(passwordT.getText());
				}else{
					impo.setSalvati(false);
				}
			}
		});
		springLayout.putConstraint(SpringLayout.NORTH, cb, 70, SpringLayout.SOUTH, passwordT);
		springLayout.putConstraint(SpringLayout.WEST, cb, 110, SpringLayout.WEST, frmAccesso.getContentPane());
		frmAccesso.getContentPane().add(cb);
		
		accedi = new JButton("Accedi");
		springLayout.putConstraint(SpringLayout.NORTH, accedi, 106, SpringLayout.SOUTH, passwordT);
		springLayout.putConstraint(SpringLayout.WEST, accedi, 159, SpringLayout.WEST, frmAccesso.getContentPane());
		springLayout.putConstraint(SpringLayout.EAST, accedi, -144, SpringLayout.EAST, frmAccesso.getContentPane());
		accedi.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				if (e.getSource() == accedi) {
					String p = String.valueOf(passwordT.getPassword());
					if (usernameT.getText().equals("")) {
						JOptionPane.showMessageDialog(null,
								"Inserisci l'Username!");
					} else if (p.equals("")) {
						JOptionPane.showMessageDialog(null,
								"Inserisci la Password!");
					} else {
						attivaCaricamento();
						new LoadAcc(usernameT.getText(),passwordT.getPassword(),frmAccesso,d).start();
					}
				}
			}
		});
		accedi.addKeyListener(this);
		usernameT.addKeyListener(this);
		passwordT.addKeyListener(this);
		accedi.setBackground(Color.LIGHT_GRAY);
		accedi.setFont(new Font("Times New Roman", Font.BOLD, 16));
		frmAccesso.getContentPane().add(accedi);

		nonRegistrato = new JLabel("Non sei registrato?");
		springLayout.putConstraint(SpringLayout.WEST, nonRegistrato, 149, SpringLayout.WEST, frmAccesso.getContentPane());
		springLayout.putConstraint(SpringLayout.EAST, nonRegistrato, -134, SpringLayout.EAST, frmAccesso.getContentPane());
		nonRegistrato.setCursor(Cursor.getPredefinedCursor(Cursor.HAND_CURSOR));
		nonRegistrato.addMouseListener(new MouseAdapter() {
			@Override
			public void mouseClicked(MouseEvent e) {
				try {
					new RegistrazioneGrafica(d);
				} catch (SQLException | IOException e1) {
					e1.printStackTrace();
				}
				frmAccesso.dispose();
			}
			@Override
			public void mouseEntered(MouseEvent e) {
				nonRegistrato.setForeground(Color.YELLOW);
			}
			@Override
			public void mouseExited(MouseEvent e) {
				nonRegistrato.setForeground(Color.BLUE);
			}
			@Override
			public void mousePressed(MouseEvent e) {
			}
		});
		nonRegistrato.setForeground(Color.BLUE);
		nonRegistrato.setHorizontalAlignment(SwingConstants.CENTER);
		nonRegistrato.setFont(new Font("Times New Roman", Font.PLAIN, 11));
		frmAccesso.getContentPane().add(nonRegistrato);

		passDimenticata = new JLabel("Password dimenticata?");
		springLayout.putConstraint(SpringLayout.WEST, passDimenticata, 149, SpringLayout.WEST, frmAccesso.getContentPane());
		springLayout.putConstraint(SpringLayout.EAST, passDimenticata, -134, SpringLayout.EAST, frmAccesso.getContentPane());
		passDimenticata.setCursor(Cursor
				.getPredefinedCursor(Cursor.HAND_CURSOR));
		springLayout.putConstraint(SpringLayout.SOUTH, passDimenticata, -38,
				SpringLayout.SOUTH, frmAccesso.getContentPane());
		springLayout.putConstraint(SpringLayout.SOUTH, nonRegistrato, -6,
				SpringLayout.NORTH, passDimenticata);
		passDimenticata.addMouseListener(new MouseAdapter() {
			@Override
			public void mouseClicked(MouseEvent e) {
				new RecuperoPasswordGrafica(d);
				frmAccesso.dispose();
			}

			@Override
			public void mouseEntered(MouseEvent e) {
				passDimenticata.setForeground(Color.YELLOW);
			}

			@Override
			public void mouseExited(MouseEvent e) {
				passDimenticata.setForeground(Color.BLUE);
			}

			@Override
			public void mousePressed(MouseEvent e) {
			}
		});
		passDimenticata.setForeground(Color.BLUE);
		passDimenticata.setHorizontalAlignment(SwingConstants.CENTER);
		passDimenticata.setFont(new Font("Times New Roman", Font.PLAIN, 11));
		frmAccesso.getContentPane().add(passDimenticata);

		userDimenticata = new JLabel("Username dimenticata?");
		springLayout.putConstraint(SpringLayout.EAST, userDimenticata, -134, SpringLayout.EAST, frmAccesso.getContentPane());
		userDimenticata.setCursor(Cursor
				.getPredefinedCursor(Cursor.HAND_CURSOR));
		springLayout.putConstraint(SpringLayout.NORTH, userDimenticata, 6,
				SpringLayout.SOUTH, passDimenticata);
		userDimenticata.addMouseListener(new MouseAdapter() {
			@Override
			public void mouseClicked(MouseEvent e) {
				new RecuperoUsernameGrafica(d);
				frmAccesso.dispose();
			}

			@Override
			public void mouseEntered(MouseEvent e) {
				userDimenticata.setForeground(Color.YELLOW);
			}

			@Override
			public void mouseExited(MouseEvent e) {
				userDimenticata.setForeground(Color.BLUE);
			}
		});
		userDimenticata.setForeground(Color.BLUE);
		userDimenticata.setHorizontalAlignment(SwingConstants.CENTER);
		userDimenticata.setFont(new Font("Times New Roman", Font.PLAIN, 11));
		frmAccesso.getContentPane().add(userDimenticata);
		
		ImageIcon imageIcon = new ImageIcon("Risorse/indicator.gif");
		caricamento = new JLabel("Connesione al Server...",imageIcon,JLabel.CENTER);
		springLayout.putConstraint(SpringLayout.NORTH, caricamento, 20, SpringLayout.SOUTH, passwordT);
		springLayout.putConstraint(SpringLayout.WEST, caricamento, 0, SpringLayout.WEST, username);
		frmAccesso.getContentPane().add(caricamento);
		caricamento.setVisible(false);
		caricaUsernameEPassword();
	}

	public void attivaCaricamento() {
		caricamento.setVisible(true);
		accedi.setVisible(false);
	}

	public void disattivaCaricamento() {
		caricamento.setVisible(false);
		accedi.setVisible(true);
	}

	class LoadAcc extends Thread {
		private String username;
		private char[] password;
		private Database d;
		private JFrame r;

		public LoadAcc(String username, char[] password,JFrame r, Database d) {
			this.username = username;
			this.password = password;
			this.d = d;
			this.r=r;
		}

		public void run() {
			try {
				Autenticazione a = new Autenticazione(username, password, d);
				int cod = a.esiste();
				if (cod == a.UTENTE_SI) {
					JOptionPane
							.showMessageDialog(null, "Connesso!");
					r.dispose();
					new GestHotel(d,username);
				} else if (cod == a.PASS_NO)
					JOptionPane.showMessageDialog(null,
							"Password errata");
				else if (cod == a.UTENTE_NO)
					JOptionPane.showMessageDialog(null,
							"Utente non registrato");
				disattivaCaricamento();
			} catch (SQLException | IOException e1) {
				disattivaCaricamento();
			} catch (ClassNotFoundException e1) {
				disattivaCaricamento();
			} catch (InvalidKeyException e) {
				disattivaCaricamento();
			} catch (NoSuchAlgorithmException e) {
				disattivaCaricamento();
			} catch (NoSuchPaddingException e) {
				disattivaCaricamento();
			} catch (IllegalBlockSizeException e) {
				disattivaCaricamento();
			} catch (BadPaddingException e) {
				disattivaCaricamento();
			} catch (NullPointerException e){
				disattivaCaricamento();
			}
		}
	}

	@Override
	public void keyTyped(KeyEvent e) {}

	@Override
	public void keyPressed(KeyEvent e) {
		if (e.getKeyCode() == KeyEvent.VK_ENTER) {
				String p = String.valueOf(passwordT.getPassword());
				if (usernameT.getText().equals("")) {
					JOptionPane.showMessageDialog(null,
							"Inserisci l'Username!");
				} else if (p.equals("")) {
					JOptionPane.showMessageDialog(null,
							"Inserisci la Password!");
				} else {
					attivaCaricamento();
					new LoadAcc(usernameT.getText(),passwordT.getPassword(),frmAccesso,d).start();
				}
		}
	}

	@Override
	public void keyReleased(KeyEvent e) {}

	@Override
	public void actionPerformed(ActionEvent e) {
		if(e.getSource()==setup){
			mostraFinestraSetup();
		}
	}

	private void mostraFinestraSetup() {
		final JFrame set=new JFrame();
		set.setSize(400,200);
		set.setLocation(500,300);
		set.setResizable(false);
		set.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
		JPanel panel1=new JPanel();
		JTabbedPane tb=new JTabbedPane();
		tb.add(panel1,"Impostazioni Grafica");
		String[] colori={"Grigio chiaro","Bianco","Nero","Verde","Giallo","Blu","Rosso","Grigio"};
		final JComboBox sceltaColore=new JComboBox(colori);
		String selezionato="";
		if(color==Color.LIGHT_GRAY){
			selezionato="Grigio chiaro";
		}else if(color==Color.RED){
			selezionato="Rosso";
		}else if(color==Color.BLUE){
			selezionato="Blu";
		}else if(color==Color.GRAY){
			selezionato="Grigio";
		}else if(color==Color.YELLOW){
			selezionato="Giallo";
		}else if(color==Color.BLACK){
			selezionato="Nero";
		}else if(color==Color.WHITE){
			selezionato="Bianco";
		}else if(color==Color.GREEN){
			selezionato="Verde";
		}
		sceltaColore.setSelectedItem(selezionato);
		JLabel colorLabel=new JLabel("Colore Tema:");
		JButton ok1=new JButton("Salva");
		ok1.addActionListener(new ActionListener(){
			public void actionPerformed(ActionEvent e) {
				if(sceltaColore.getSelectedItem().equals("Bianco")) frmAccesso.getContentPane().setBackground(Color.WHITE);
				else if(sceltaColore.getSelectedItem().equals("Nero")) frmAccesso.getContentPane().setBackground(Color.BLACK);
				else if(sceltaColore.getSelectedItem().equals("Grigio chiaro")) frmAccesso.getContentPane().setBackground(Color.LIGHT_GRAY);
				else if(sceltaColore.getSelectedItem().equals("Verde")) frmAccesso.getContentPane().setBackground(Color.GREEN);
				else if(sceltaColore.getSelectedItem().equals("Giallo")) frmAccesso.getContentPane().setBackground(Color.YELLOW);
				else if(sceltaColore.getSelectedItem().equals("Blu")) frmAccesso.getContentPane().setBackground(Color.BLUE);
				else if(sceltaColore.getSelectedItem().equals("Rosso")) frmAccesso.getContentPane().setBackground(Color.RED);
				else if(sceltaColore.getSelectedItem().equals("Grigio")) frmAccesso.getContentPane().setBackground(Color.GRAY);
				set.dispose();
				color=frmAccesso.getContentPane().getBackground();
				try {
					salvaColore();
				} catch (FileNotFoundException e1) {
					e1.printStackTrace();
				}
			}
		});
		panel1.add(colorLabel);
		panel1.add(sceltaColore);
		panel1.add(ok1);
		JPanel panel2=new JPanel();
		tb.add(panel2,"Server IP");
		JLabel ind=new JLabel("Indirizzo IP del Server");
		panel2.add(ind);
		final JTextField indJ=new JTextField(impo.getIP(),16);
		panel2.add(indJ);
		JLabel por=new JLabel("Porta");
		final JTextField porJ=new JTextField(impo.getPorta()+"",6);
		panel2.add(por);
		panel2.add(porJ);
		JButton ok2=new JButton("Salva");
		ok2.addActionListener(new ActionListener(){
			public void actionPerformed(ActionEvent e) {
				impo.setIP(indJ.getText());
				impo.setPorta(Integer.parseInt(porJ.getText()));
				set.dispose();
			}
		});
		panel2.add(ok2);
		set.add(tb);
		set.setVisible(true);
	}
}
